package com.fulihui.usercore.core.repository.impl;

import com.fulihui.usercore.core.repository.UserLoginRepository;
import com.fulihui.usercore.dal.dataobj.LoginDO;
import com.fulihui.usercore.dal.dataobj.LoginHelpDO;
import com.fulihui.usercore.dal.dataobj.LoginHelpDOExample;
import com.fulihui.usercore.dal.mapper.LoginHelpDOMapper;
import com.fulihui.usercore.dal.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Willard.Hu on 2016/5/29.
 */
@Repository
public class UserLoginRepositoryImpl implements UserLoginRepository {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private LoginHelpDOMapper loginHelpDOMapper;

    /**
     * @see UserLoginRepository#insert(LoginDO)
     */
    @Override
    public void insert(LoginDO loginDO) {

        loginMapper.insert(loginDO);
        LoginHelpDOExample example = new LoginHelpDOExample();
        example.createCriteria().andLoginIdEqualTo(loginDO.getLoginId());
        List<LoginHelpDO> loginHelpDOS = loginHelpDOMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(loginHelpDOS)) {
            LoginHelpDO record = new LoginHelpDO();
            record.setLoginId(loginDO.getLoginId());
            record.setUserId(loginDO.getUserId());
            loginHelpDOMapper.insert(record);
        }

    }

    /**
     * @see UserLoginRepository#update(LoginDO)
     */
    @Override
    public boolean update(LoginDO loginDO) {
        return loginMapper.update(loginDO);
    }

    @Override
    public boolean updateLoginId(LoginDO loginDO) {
        return loginMapper.updateLoginId(loginDO);
    }

    /**
     * @see UserLoginRepository#queryByUserId(String)
     */
    @Override
    public LoginDO queryByUserId(String userId) {
        return loginMapper.queryByUserid(userId);
    }

    /**
     * @see UserLoginRepository#queryByPK(String)
     */
    @Override
    public LoginDO queryByPK(String loginId) {
        //fixme 替换原方法，改查辅助表
        LoginHelpDOExample example = new LoginHelpDOExample();
        example.createCriteria().andLoginIdEqualTo(loginId);
        List<LoginHelpDO> loginHelpDOS = loginHelpDOMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(loginHelpDOS)) {
            return loginMapper.queryByUserid(loginHelpDOS.get(0).getUserId());
        }
        return null;
    }

    @Override
    public boolean updatePasswordByUserId(LoginDO loginDO) {
        return loginMapper.updatePasswordByUserId(loginDO);
    }

}
